#!/bin/sh

# Global S2I variable setup
source `dirname "$0"`/s2i-setup

# Always include jolokia-opts, which can be empty if switched off via env
JAVA_OPTIONS=${JAVA_OPTIONS:+${JAVA_OPTIONS} }

# TODO add jolokia and prometheus
# $(/opt/jolokia/jolokia-opts) $(/opt/prometheus/prometheus-opts)"

# Temporary options variable until the harmonization hawt-app PR #5 has been applied (hopefully)
JVM_ARGS="${JVM_ARGS:+${JVM_ARGS} }${JAVA_OPTIONS}"
export JAVA_OPTIONS JVM_ARGS

# support JBoss Tools OpenShift debug environment variables
export JAVA_DEBUG="${JAVA_DEBUG:-${DEBUG}}"
if [ "x${JAVA_DEBUG}" != x ]; then
  export JAVA_DEBUG_PORT="${JAVA_DEBUG_PORT:-${DEBUG_PORT}}"
fi
# SpringBoot also uses DEBUG variable, so shade it with SPRINGBOOT_DEBUG variable
if [ "x${SPRINGBOOT_DEBUG}" != x ]; then
	export DEBUG="${SPRINGBOOT_DEBUG}"
else
	unset DEBUG
fi

# check for SpringBoot exploded archive
if [ -f "${DEPLOYMENTS_DIR}/META-INF/MANIFEST.MF" ]; then
	echo "SpringBoot exploded archive detected..."
	if [ "x${JAVA_DEBUG}" != x ]; then
		# setup classpath and start class as main class
		if [ "x${JAVA_CLASSPATH}" = x ]; then
			JAVA_CLASSPATH="${DEPLOYMENTS_DIR}/BOOT-INF/lib/*"
		else
			JAVA_CLASSPATH="${DEPLOYMENTS_DIR}/BOOT-INF/lib/*:${JAVA_CLASSPATH}"
		fi
		export JAVA_CLASSPATH="${DEPLOYMENTS_DIR}/BOOT-INF/classes/:${JAVA_CLASSPATH}"
		# setup start class as main class
		main_class=`sed -n 's/Start-Class: \(.*\)$/\1/p' "${DEPLOYMENTS_DIR}/META-INF/MANIFEST.MF" | tr -d '[[:space:]]'`
	fi
	# default to SpringBoot's Main-Class
	if [ "x${main_class}" = x ]; then
		main_class=`sed -n 's/Main-Class: \(.*\)$/\1/p' "${DEPLOYMENTS_DIR}/META-INF/MANIFEST.MF" | tr -d '[[:space:]]'`
	fi
	echo "Starting SpringBoot application with main class ${main_class}"
	export JAVA_MAIN_CLASS="${main_class}"
fi

if [ -f "${DEPLOYMENTS_DIR}/bin/run.sh" ]; then
    echo "Starting the application using the bundled ${DEPLOYMENTS_DIR}/bin/run.sh ..."
    exec ${DEPLOYMENTS_DIR}/bin/run.sh "$@" ${JAVA_ARGS}
else
    echo "Starting the Java application using /opt/run-java/run-java.sh ..."
    exec /opt/run-java/run-java.sh "$@" ${JAVA_ARGS}
fi
